from PIL import Image as ImagePIL
import os
import fitz
import re
import glob



def frompic2pdf(img_path, pdf_path, pdf_name):
    # print(img_path + pdf_name + '.jpg')
    # 使用glob读图
    for img in os.listdir(img_path):
        # 打开空文档
        doc = fitz.open()
        # 打开指定图片
        imgdoc = fitz.open(img_path + "/" + img)
        # 使用图片创建单页的PDF
        pdfbytes = imgdoc.convert_to_pdf()
        imgpdf = fitz.open("pdf", pdfbytes)
        # 将当前页写入文档
        doc.insert_pdf(imgpdf)
        # 保存为指定名称的PDF文件
        doc.save(pdf_path + "/" + pdf_name + '.pdf')
        # 关闭
        doc.close()


def transfer(infile, outfile):
    im = ImagePIL.open(infile)
    im = im.transpose(2)
    im.save(outfile, dpi=(400.0, 400.0))  ##500.0,500.0分别为想要设定的dpi值


def pdf2image1(path, pic_path):
    checkim = r"/Subtype(?= */Image)"
    pdf = fitz.open(path)
    lenxref = pdf.xref_length()
    count = 1
    for i in range(1, lenxref):
        text = pdf.xref_object(i)
        isimage = re.search(checkim, text)
        if not isimage:
            continue
        pix = fitz.Pixmap(pdf, i)
        if pix.size < 10000:  # 在这里添加一处判断一个循环
            continue  # 不符合阈值则跳过至下
        new_name = f"{count}.png"
        pix.save("./" + pic_path + "/" + new_name)
        transfer("./" + pic_path + "/" + new_name, "./" + pic_path + "/" + new_name)
        count += 1


if __name__ == '__main__':
    for file in os.listdir("."):
        if ".pdf" not in file:
            continue
        print(file)
        # 创建临时文件夹
        path = file.replace(".pdf", "")
        try:
            os.mkdir(path)
        except Exception as e:
            print(e)
        pdf2image1(file, path)
        # 生成结果
        result_path = "./result"
        try:
            os.mkdir(result_path)
        except Exception as e:
            print(e)
        frompic2pdf(path, result_path, file.split(".")[0])
        # 清理文件夹
        try:
            os.rmdir(path)
        except Exception as e:
            print(e)
    print("done")
